package com.tyc.mb.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.tyc.mb.common.LogData;
import com.tyc.mb.common.interceptor.DataSourceSelector;
import com.tyc.mb.exception.BaseException;
import com.tyc.mb.mapper.UserMapper;
import com.tyc.mb.config.DataSourceContextHolder;
import com.tyc.mb.model.LogType;
import com.tyc.mb.model.User;
import com.tyc.mb.model.response.ResultCode;
import com.tyc.mb.service.BloomFilterService;
import com.tyc.mb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tyc.mb.common.util.*;

import java.util.List;

/**
 * 类描述
 *
 * @author tyc
 * @version 1.0
 * @date 2021-10-25 18:27:11
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BloomFilterService bloomFilterService;


    @Override
    @DataSourceSelector
    public User getUserById(Integer sid, Integer id) {
        User user = userMapper.getUserById(id);
        if(null == user){
            throw new BaseException(ResultCode.USER_NOT_FOUND);
        }
        return user;
    }

    @Override
    @DataSourceSelector
    public User getUserByName(String userName) {
        if(!bloomFilterService.userNameExist(userName)){
            throw new BaseException(ResultCode.USER_NOT_FOUND);
        }
        return userMapper.getUserByName(userName);
    }

    @Override
    @DataSourceSelector
    public Long login(User user, Integer sid) {
        User userData = userMapper.getUserByName(user.getName());
        if(null == userData || !checkPassword(user.getPassword(), userData.getPassword())){
            throw new BaseException(ResultCode.USER_LOGIN_FAILED);
        }
        // 记录用户登录日志
        LogData.record(LogType.LOGIN, JSONObject.toJSONString(userData));
        return userData.getId();
    }


    @Override
    @DataSourceSelector
    public Long register(User user, Integer sid) {
        if(userMapper.countByName(user.getName()) > 1){
            throw new BaseException(ResultCode.USER_NAME_EXITS);
        }
        String pwd = "";
        try {
             pwd = RSAEncrypt.decrypt(user.getPassword());
        } catch (Exception e) {
            throw new BaseException(ResultCode.DECODE_ERROR, "password error");
        }
        user.setPassword(Bcypt.encode(pwd));

        userMapper.save(user);
        return user.getId();
    }

    @Override
    public List<User> getAll() {
        return userMapper.getAll();
    }


    private boolean checkPassword(String inputPwd, String dataSourcePwd){
        String pwd = "";
        try {
            // RSA 解密
            pwd = RSAEncrypt.decrypt(inputPwd);
        } catch (Exception e) {
            throw new BaseException(ResultCode.DECODE_ERROR);
        }
        return Bcypt.matches(pwd,dataSourcePwd);
    }
}
